/* eslint-disable @typescript-eslint/ban-ts-comment */
import React, { useEffect, useRef, useState } from 'react';
import Strings from '@/i18n';
import { useDpSchema, useDevice } from '@ray-js/panel-sdk';
import { Text, View, Image, getAnalyticsLogsStatusLog, ScrollView } from '@ray-js/ray';
import { NavBarCustom } from '@/components/NavBarCustom';
import { Dialog, DialogInstance } from '@ray-js/smart-ui';
import { useDispatch } from 'react-redux';
import { useSwitchInfo } from '@/hooks/useSwitchInfo';
import res from '@/res/images';
import { updateSwtichName, updateSwtichPic } from '@/redux/modules/cloudStateSlice';
import { saveCloudData } from '@/api';
import { parseCustomString } from '@/utils/parse';
import { handleAvatar } from '@/utils/avatar';
import { getCachedSystemInfo } from '@/api/getCachedSystemInfo';
import { log } from './mock';
import styles from './index.module.less';
import dayjs from 'dayjs';
import { useDebounceFn } from 'ahooks';

const formatLogs = (logs: any[]) => {
  const steps = logs.map(item => {
    const { type, booleanValue } = parseCustomString(item.value);
    return {
      text: type,
      desc: booleanValue ? Strings.getLang('on') : Strings.getLang('off'),
    };
  });
  return steps;
};

const { safeArea } = getCachedSystemInfo();

const { height } = safeArea;

const LogPage: React.FC = ({
  location,
}: {
  location: {
    query: {
      switchId: string;
      nextTime?: string;
      waterTime?: string;
    };
  };
}) => {
  const dps = useSwitchInfo();

  const { query } = location;

  const {
    switchId = 'switch_1',
    nextTime = '--',
    waterTime = '--',
  } = query || { switchId: 'switch_1' };

  console.log('🚀 ~ LogPage ~ switchId:', switchId);

  const dispatch = useDispatch();

  const current = dps.find(item => item.dpId === switchId);

  console.log('🚀 ~ LogPage ~ dps:', dps);

  const changeName = () => {
    const beforeClose = (
      action: 'cancel' | 'confirm' | 'overlay',
      value?: string
    ): Promise<boolean> =>
      new Promise(resolve => {
        setTimeout(() => {
          if (action === 'confirm') {
            dispatch(
              updateSwtichName({
                [switchId]: value,
              })
            );

            saveCloudData({
              code: switchId,
              value: {
                name: value,
                pic: current.pic || '',
              },
            });

            resolve(true);
          } else {
            // 拦截取消操作
            resolve(true);
          }
        }, 10);
      });
    DialogInstance.input({
      title: '请输入名称',
      selector: `#smart-dialog-switchId`,
      value: current?.name || '',
      beforeClose,
      cancelButtonText: Strings.getLang('cancel'),
      confirmButtonText: Strings.getLang('confirm'),
    });
  };

  const changeAvatar = async () => {
    const res = await handleAvatar();
    if (res) {
      dispatch(
        updateSwtichPic({
          [switchId]: res.path,
        })
      );
      saveCloudData({
        code: switchId,
        value: {
          name: current?.name || '',
          pic: res.publicUrl,
        },
      });
    }
  };

  const name = current?.name;

  const pic = current?.pic || '';

  const { devId } = useDevice(d => d.devInfo);

  const schema = useDpSchema();

  const dpId = schema[current.logCode]?.id || '107';

  const [logs, setLogs] = useState([]);

  const [hasNext, setHasNext] = useState(false);

  const offset = useRef(0);

  const getLogs = useDebounceFn(
    (init?: boolean) => {
      if (!hasNext && !init) {
        return;
      }

      ty.showLoading({ title: '' });

      getAnalyticsLogsStatusLog({
        devId,
        dpIds: String(dpId),
        offset: offset.current,
        limit: 20,
        sortType: 'desc',
      })
        .then(respo2nse => {
          const response = respo2nse;

          offset.current = response.hasNext ? offset.current + 20 : offset.current;

          const newLogs = [...logs, ...(response?.dps || [])].sort(
            (a, b) => b.timeStamp - a.timeStamp
          );

          setLogs(newLogs);
          setHasNext(Boolean(response.hasNext));
          ty.hideLoading();
        })
        .catch(() => {
          ty.hideLoading();
        });
    },
    { wait: 500 }
  ).run;

  useEffect(() => {
    getLogs(true);
  }, []);

  return (
    <View className={styles.view}>
      <NavBarCustom name={Strings.getLang('record')} back />

      <View className={styles.currentBox}>
        <Image src={pic} className={styles.currentPic} />
        <View className={styles.currentName}>
          <View className={styles.name} onClick={changeName}>
            <Text className={styles.nameText}>{name}</Text>
          </View>

          <View
            className={styles.changePic}
            onClick={() => {
              changeName();
            }}
          >
            {Strings.getLang('changeName')}
          </View>
        </View>
      </View>

      <View className={styles.section}>
        <Text className={styles.next}>{Strings.getLang('next_irrigation_time')}</Text>
        <View className={styles.dateArea}>
          <Text className={styles.dateText}>
            {nextTime != '0' ? dayjs(Number(nextTime)).format('YYYY/MM/DD HH:mm') : '--'}
          </Text>
          <View className={styles.remainBox}>
            <Text className={styles.remainText}>
              {`${Strings.getLang('remainTime')} ${waterTime}`}
            </Text>
          </View>
        </View>
      </View>

      <ScrollView
        onScrollToLower={() => {
          getLogs();
        }}
        lowerThreshold={200}
        style={{
          height: `calc(${height}px - 230px - env(safe-area-inset-bottom) / 2  )`,
          width: '710rpx',
          margin: '0 auto',
          marginTop: '20rpx',
          borderRadius: '24rpx',
        }}
        scrollY
        hideScrollbar
      >
        <View className={styles.logBox}>
          {logs.map((item, index) => {
            const { type, booleanValue } = parseCustomString(item.value);
            return (
              <View key={`${item.timeStamp}${index}`} className={styles.list}>
                <View className={styles.circle} />
                <View className={styles.timeText}>{item.timeStr}</View>
                <View className={styles.waterTime}>
                  <Text className={styles.typeText}>{Strings.getLang(type)}</Text>
                  <Text className={styles.statusText}>
                    {booleanValue ? Strings.getLang('turn_on') : Strings.getLang('turn_off')}
                  </Text>
                </View>
                {index !== logs.length - 1 && <View className={styles.line} />}
              </View>
            );
          })}

          {logs.length === 0 ? (
            <View className={styles.empty}>
              <Image src={res.empty} className={styles.emptyImage} />
              <Text className={styles.emptyText}>{Strings.getLang('no_log')}</Text>
            </View>
          ) : null}
        </View>
      </ScrollView>

      <Dialog id="smart-dialog-switchId" />
    </View>
  );
};

export default LogPage;
